﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CommunityServer.WebServices.MediaGalleries;
using System.Runtime.InteropServices;
using System.IO;
using System.Threading;
using System.Web;
namespace nb.development.csmediamanager
{
    public partial class NewPost : Form
    {
        private MediaGallery gallery; private Guid siteid;
        public NewPost(MediaGallery gallery, Guid siteid, string tag)
        {
            InitializeComponent();
            this.gallery = gallery;
            this.siteid = siteid;
            singleAttachment.Gallery = gallery;
            singleAttachment.SiteId = siteid;
            multiAttachmentPicker1.Gallery = gallery;
            multiAttachmentPicker1.SiteId = siteid;
            if (!string.IsNullOrEmpty(tag))
            {
                singleTags.Text = tag;
                multiTags.Text = tag;
                dirTags.Text = tag;
            }
        }

        private void dirBrowser_Click(object sender, EventArgs e)
        {
            if (folder.ShowDialog() == DialogResult.OK)
            {
                dirPath.Text = folder.SelectedPath;
                if (dirTags.Text.Length > 0) dirTags.Text += ", " + folder.SelectedPath.Remove(0, folder.SelectedPath.LastIndexOf('\\') + 1);
                else dirTags.Text = folder.SelectedPath.Remove(0, folder.SelectedPath.LastIndexOf('\\') + 1);
                dirFiles.Nodes.Clear();
                foreach (FileInfo file in new DirectoryInfo(folder.SelectedPath).GetFiles("*", SearchOption.TopDirectoryOnly))
                    if (!file.Extension.ToLower().Equals(".ini") && !file.Extension.ToLower().Equals(".db"))
                        dirFiles.Nodes.Add(file.Name.Remove(file.Name.LastIndexOf('.')));
                checkDirectory();
            }
        }

        private bool checkDirectory()
        {
            if (dirPath.Text.Length > 0)
            {
                btnOK.Enabled = true;
                return true;
            }
            btnOK.Enabled = false;
            return false;
        }

        private bool checkMulti()
        {
            if (((MultiAttachmentPicker)multiPosts.Controls[0]).Uploaded)
            {
                btnOK.Enabled = true;
                return true;
            }
            btnOK.Enabled = false;
            return false;
        }

        private bool checkSingle()
        {
            if (singleAttachment.Enabled == true && singleTitle.Text.Length > 0 && uploadtabs.SelectedIndex == 0)
            {
                btnOK.Enabled = true;
                return true;
            }
            btnOK.Enabled = false;
            return false;
        }

        private void singleAttachment_UploadCompleted(object sender)
        {
            singleAttachment.Text = singleAttachment.Filename;
            checkSingle();
        }

        private void multiAttachment_UploadCompleted(object sender)
        {
            MultiAttachmentPicker a = new MultiAttachmentPicker();
            MultiAttachmentPicker b = sender as MultiAttachmentPicker;
            a.UploadCompleted += new TemporaryMediaUploaded(multiAttachment_UploadCompleted);
            a.DeleteClicked += new MouseEventHandler(multiAttachmentPicker1_DeleteClicked);
            a.AttachmentButtonText = b.AttachmentButtonText;
            a.Gallery = b.Gallery;
            a.SiteId = b.SiteId;
            a.Width = b.Width;
            a.Height = b.Height;
            multiPosts.Controls.Add(a);
            b.AttachmentButtonText = b.Filename;
            checkMulti();
        }

        private void multiAttachmentPicker1_DeleteClicked(object sender, MouseEventArgs e)
        {
            MultiAttachmentPicker map = sender as MultiAttachmentPicker;
            if (map.Uploaded)
                multiPosts.Controls.Remove(map);
            checkMulti();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            uploadtabs.Enabled = false;
            btnCancel.Enabled = false;
            btnOK.Enabled = false;
            ControlBox = false;
            if (uploadtabs.SelectedIndex < 2)
            {
                Uploader u;
                List<MediaGalleryPost> posts = new List<MediaGalleryPost>();
                if (uploadtabs.SelectedIndex == 0)
                {
                    MediaGalleryPost post = new MediaGalleryPost(singleAttachment.TemporaryGuid);
                    post.Title = HttpUtility.HtmlEncode(singleTitle.Text);
                    post.Body = HttpUtility.HtmlEncode(string.IsNullOrEmpty(singleDesc.Text) ? "Uploaded By CS Media Manager" : singleDesc.Text);
                    post.MediaGalleryId = gallery.Id;
                    foreach (string s in singleTags.Text.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                        post.Keywords.Add(HttpUtility.HtmlEncode(s.Trim()));
                    posts.Add(post);
                }
                else if (uploadtabs.SelectedIndex == 1)
                {
                    foreach (MultiAttachmentPicker picker in multiPosts.Controls)
                        if (picker.Uploaded)
                        {
                            MediaGalleryPost post = new MediaGalleryPost(picker.TemporaryGuid);
                            post.Title = picker.Filename;
                            post.MediaGalleryId = gallery.Id;
                            post.Body = HttpUtility.HtmlEncode("Multiple Posts Uploaded By CS Media Manager");
                            foreach (string s in multiTags.Text.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                                post.Keywords.Add(HttpUtility.HtmlEncode(s.Trim()));
                            posts.Add(post);
                        }
                }
                u = new Uploader(posts, this.siteid);
                uploadProgs.Maximum = posts.Count;
                u.UploadedPost += new UploadedPost(u_UploadedPost);
                u.UploadCompleded += new UploadCompleted(u_UploadCompleded);
                uploadProgs.Value = 0;
                uploading.Show();
                Thread t = new Thread(new ThreadStart(u.Upload));
                t.Start();
            }
            else
            {
                Uploader u;
                List<FileInfo> files = new List<FileInfo>();
                List<ImageAlterations> images = new List<ImageAlterations>();
                foreach (FileInfo file in new DirectoryInfo(dirPath.Text).GetFiles("*", SearchOption.TopDirectoryOnly))
                    if (!file.Extension.ToLower().Equals(".ini") && !file.Extension.ToLower().Equals(".db"))
                    {
                        if (groupBox1.Height == 16)
                            files.Add(file);
                        else
                        {
                            if (file.Extension.ToLower().Equals(".png") || file.Extension.ToLower().Equals(".jpg") || file.Extension.ToLower().Equals(".jpeg") || file.Extension.ToLower().Equals(".gif") || file.Extension.ToLower().Equals(".bmp"))
                            {
                                if (dirIMGResize.SelectedItem.ToString().StartsWith("--") && dirIMGResize.Text.Equals("Select...") && efx == null)
                                    files.Add(file);
                                else
                                {
                                    ImageAlterations i = new ImageAlterations();
                                    i.File = file;
                                    if (!dirIMGResize.SelectedText.StartsWith("--") && !dirIMGResize.Text.Equals("Select..."))
                                    {
                                        i.Resize = true;
                                        i.ResizeDimensions = new Point(int.Parse(dirIMGResize.SelectedItem.ToString().Split(' ')[0].Split('x')[0]), int.Parse(dirIMGResize.SelectedItem.ToString().Split(' ')[0].Split('x')[1]));
                                    }
                                    if (efx != null)
                                    {
                                        i.Watermark = true;
                                        i.WatermarkColor = efx.WatermarkColor;
                                        i.WatermarkFont = efx.Watermarkfont;
                                        i.WatermarkPosition = efx.Watermarkposition;
                                        i.WatermarkText = efx.Watermarktext;
                                    }
                                    images.Add(i);
                                }
                            }
                            else files.Add(file);
                        }
                    }
                if (images.Count > 0) u = new Uploader(files, this.siteid, images, gallery.Id, dirTags.Text);
                else u = new Uploader(files, this.siteid, gallery.Id, dirTags.Text);
                uploadProgs.Maximum = files.Count + images.Count;
                u.UploadedPost += new UploadedPost(u_UploadedPost);
                u.UploadCompleded += new UploadCompleted(u_UploadCompleded);
                uploadProgs.Value = 0;
                uploading.Show();
                Thread t;
                if (images.Count > 0) t = new Thread(new ThreadStart(u.UploadDirectoryWithImages));
                else t = new Thread(new ThreadStart(u.UploadDirectory));
                t.Start();
            }
        }

        void u_UploadCompleded()
        {
            if (this.InvokeRequired)
            {
                UploadCompleted done = new UploadCompleted(u_UploadCompleded);
                try { this.Invoke(done); }
                catch { }
            }
            else { this.DialogResult = DialogResult.OK; this.Close(); }
        }

        void u_UploadedPost(int index, int count)
        {
            if (uploadProgs.InvokeRequired)
            {
                UploadedPost done = new UploadedPost(u_UploadedPost);
                try { this.Invoke(done, index, count); }
                catch { }
            }
            else uploadProgs.Value = index;
        }

        private void uploadtabs_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (uploadtabs.SelectedIndex == 0)
                checkSingle();
            else if (uploadtabs.SelectedIndex == 1)
                checkMulti();
            else checkDirectory();
            if (efx != null) { efx.Close(); efx = null; } 
        }

        private void singleTitle_KeyUp(object sender, KeyEventArgs e)
        {
            checkSingle();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void dirIMGEx_MouseHover(object sender, EventArgs e)
        {
            if (groupBox1.Height == 16)
                dirIMGEx.Image = Properties.Resources.group_expand_over;
            else dirIMGEx.Image = Properties.Resources.group_collapse_over;
        }

        private void dirIMGEx_MouseDown(object sender, MouseEventArgs e)
        {
            if (groupBox1.Height == 16)
                dirIMGEx.Image = Properties.Resources.group_expand_down;
            else dirIMGEx.Image = Properties.Resources.group_collapse_down;
        }

        private void dirIMGEx_MouseClick(object sender, MouseEventArgs e)
        {
            if (groupBox1.Height == 16)
            {
                dirIMGEx.Image = Properties.Resources.group_collapse;
                groupBox1.Height = 50;
            }
            else
            {
                dirIMGEx.Image = Properties.Resources.group_expand;
                groupBox1.Height = 16;
            }
        }

        private void dirIMGEx_MouseLeave(object sender, EventArgs e)
        {
            if (groupBox1.Height == 16)
                dirIMGEx.Image = Properties.Resources.group_expand;
            else dirIMGEx.Image = Properties.Resources.group_collapse;
        }

        private Effects efx;

        private void dirIMGEffects_Click(object sender, EventArgs e)
        {
            efx = new Effects();
            efx.EffectChanged += new EffectChangeHandler(efx_EffectChanged);
            efx.Show(this);
            efx.SetDesktopLocation(this.Location.X + this.Width + 10, this.Location.Y + 10);
        }

        void efx_EffectChanged()
        {
        }
        
    }
}
